package com.icepeach.icepeachhomeback.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.icepeach.icepeachhomeback.dto.UserDto;
import com.icepeach.icepeachhomeback.entity.User;
import com.icepeach.icepeachhomeback.service.UserService;
import com.icepeach.icepeachhomeback.util.ApiResult;
import com.icepeach.icepeachhomeback.util.TokenUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/loginAndRegister")
public class LoginAndRegisterController {
    @Resource
    UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public ApiResult login(@RequestBody  User user){
        // 校验用户名和密码是否为空
        if (StrUtil.isEmpty(user.getUsername())) {
            return ApiResult.failure("请输入用户名");
        }
        if (StrUtil.isEmpty(user.getPassword())) {
            return ApiResult.failure("请输入密码");
        }

        // 根据用户名查找用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        User dbUser = userService.getOne(userQueryWrapper);
        if (dbUser == null) {
            return ApiResult.failure("该账号不存在");
        }
        UserDto userDto=new UserDto();
        BeanUtil.copyProperties(dbUser,userDto,true);
        String token = TokenUtils.getToken(dbUser.getId(),dbUser.getPassword());
        userDto.setToken(token);
        // 校验密码是否正确
        if (!SecureUtil.md5(user.getPassword()).equals(dbUser.getPassword())) {
            return ApiResult.failure("密码错误");
        }

        // 登录成功
        return ApiResult.success("登录成功", userDto);

    }
    @PostMapping("/register")
    @ResponseBody
    public ApiResult<Boolean> register(@RequestBody User userRegisterReq) {
        // 检查用户名是否已存在
        User dbUser = userService.getOne(new QueryWrapper<User>().eq("username",userRegisterReq.getUsername()));
        if (dbUser != null) {
            return ApiResult.failure("用户名已存在");
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(userRegisterReq.getUsername());
        newUser.setPassword(SecureUtil.md5(userRegisterReq.getPassword()));

        // 保存用户信息
        boolean success = userService.save(newUser);
        if (!success) {
            return ApiResult.failure("注册失败");
        }

        return ApiResult.success("注册成功", true);
    }

}
